<template>
  <view class="container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <text class="header-title">我的发布</text>
      <view class="publish-btn-container">
        <button 
          class="publish-btn" 
          type="default" 
          size="mini" 
          @click="handlePublish"
        >
          <text class="publish-btn-text">发布物品</text>
        </button>
      </view>
    </view>

    <!-- 加载/错误/状态提示 -->
    <view class="loading-banner" v-if="isLoading">
      <icon type="loading" size="18" color="#4A90E2" />
      <text class="banner-text">加载中...</text>
    </view>
    <view class="error-banner" v-if="errorMsg && !isLoading">
      <icon type="warn" size="18" color="#F56C6C" />
      <text class="error-text">{{errorMsg}}</text>
    </view>

    <!-- 6分类筛选标签 -->
    <view class="filter-tabs">
      <view 
        class="tab-item" 
        :class="{active: activeTab === 'all'}"
        @click="activeTab = 'all'"
      >全部</view>
      <view 
        class="tab-item" 
        :class="{active: activeTab === 'pending'}"
        @click="activeTab = 'pending'"
      >未通过</view>
      <view 
        class="tab-item" 
        :class="{active: activeTab === 'approved'}"
        @click="activeTab = 'approved'"
      >通过</view>
      <view 
        class="tab-item" 
        :class="{active: activeTab === 'completed'}"
        @click="activeTab = 'completed'"
      >完成</view>
      <view 
        class="tab-item" 
        :class="{active: activeTab === 'offline'}"
        @click="activeTab = 'offline'"
      >下架</view>
      <view 
        class="tab-item" 
        :class="{active: activeTab === 'rejected'}"
        @click="activeTab = 'rejected'"
      >驳回</view>
    </view>

    <!-- 发布列表 -->
    <scroll-view class="list-container" scroll-y>
      <view class="empty-tip" v-if="isLoading">
        <icon type="loading" size="60" color="#4A90E2" />
        <text class="empty-text">加载数据中...</text>
      </view>
      <view class="empty-tip" v-else-if="filteredList.length === 0 && !errorMsg">
        <icon type="info" size="60" color="#4A90E2" />
        <text class="empty-text">暂无发布记录</text>
        <text class="empty-subtext">点击右上角发布物品</text>
      </view>

      <!-- 卡片式布局 -->
      <view 
        class="item-card" 
        v-for="item in filteredList" 
        :key="item.itemId"
        @mouseenter="handleMouseEnter(item.itemId)"
        @mouseleave="handleMouseLeave"
        :class="{ 'card-hover': hoveredItem === item.itemId }"
      >
        <!-- 左侧图片 -->
        <view class="item-image-container">
          <image 
            :src="item.itemImage" 
            class="item-image" 
            mode="aspectFill"
            @error="handleImageError"
          ></image>
          <!-- 物品类型标签（丢失/拾到） -->
          <view 
            class="item-type-tag"
            :style="{ backgroundColor: item.itemType === 'Lost' ? '#FF4D4F' : '#52C41A' }"
          >
            <text>{{getItemTypeText(item.itemType)}}</text>
          </view>
        </view>
        
        <!-- 右侧信息（包含底部操作栏） -->
        <view class="item-info-container">
          <view class="item-header">
            <text class="item-title">{{item.itemName}}</text>
            <view 
              class="status-tag" 
              :style="{backgroundColor: getStatusBgColor(item.status), color: getStatusTextColor(item.status)}"
            >
              {{getStatusText(item.status)}}
            </view>
          </view>
          
          <!-- 物品描述，增加高度限制 -->
          <text class="item-desc">{{item.itemDescription}}</text>
          
          <!-- 位置信息 -->
          <view class="item-location">
            <icon type="location" size="22" color="#4A90E2" />
            <text class="location-text">{{formatLocation(item.itemLocation)}}</text>
          </view>

          <!-- 底部操作栏 -->
          <view class="item-footer">
            <view class="footer-time">
              <text class="item-time">{{formatTime(item.createTime)}}</text>
            </view>
            <view class="action-btns-row">
              <view 
                v-if="getActionButtons(item).length > 0" 
                class="action-buttons"
              >
                <view 
                  v-for="(btn, index) in getActionButtons(item)" 
                  :key="index" 
                  :class="{
                    'action-btn': true,
                    'single-btn': getActionButtons(item).length === 1,
                    'double-btn': getActionButtons(item).length === 2,
                    'triple-btn': getActionButtons(item).length === 3,
                    'btn-delete': btn.type === 'delete',
                    'btn-offline': btn.type === 'offline',
                    'btn-online': btn.type === 'online',
                    'btn-detail': btn.type === 'detail'
                  }"
                  @click="handleAction(btn, item)"
                >
                  <text class="action-btn-text">{{btn.text}}</text>
                </view>
              </view>
              <view v-else class="no-actions">暂无操作</view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="bottom-space"></view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';

// 物品实体类
interface BaseItem {
  itemId: number;
  itemName: string;
  itemType: string; // Lost-丢失/Found-拾到
  itemDescription: string;
  itemLocation: string; // 位置坐标或地址
  itemImage: string; // 图片URL
  createTime: Date;
  status: number; // 1-未通过，2-通过，3-完成，4-下架，5-驳回
}

// 接口基础URL
const BASE_URL = 'http://172.20.10.2:8080/api';

const activeTab = ref<'all' | 'pending' | 'approved' | 'completed' | 'offline' | 'rejected'>('all');
const itemList = ref<BaseItem[]>([]);
const hoveredItem = ref<number | null>(null);
const isLoading = ref<boolean>(false);
const errorMsg = ref<string | null>(null);

// 筛选逻辑
const statusMap: Record<string, number[]> = {
  all: [1, 2, 3, 4, 5],
  pending: [1],
  approved: [2],
  completed: [3],
  offline: [4],
  rejected: [5]
};

// 计算属性：筛选后的列表
const filteredList = computed(() => {
  return itemList.value.filter(item => 
    statusMap[activeTab.value].includes(item.status)
  );
});

// 状态文案
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    1: '未通过',
    2: '通过',
    3: '完成',
    4: '下架',
    5: '驳回'
  };
  return statusMap[status] || '';
};

// 状态背景色
const getStatusBgColor = (status: number) => {
  const colorMap: Record<number, string> = {
    1: '#FFF2F0', // 红色-未通过
    2: '#F0FFF4', // 绿色-通过
    3: '#E6F7ED', // 深绿-完成
    4: '#F5F7FA', // 灰色-下架
    5: '#FFF7E6', // 黄色-驳回
  };
  return colorMap[status] || '#F5F9FF';
};

// 状态文字颜色
const getStatusTextColor = (status: number) => {
  const colorMap: Record<number, string> = {
    1: '#F5222D', // 红色
    2: '#52C41A', // 绿色
    3: '#389E0D', // 深绿
    4: '#86909C', // 灰色
    5: '#FAAD14', // 黄色
  };
  return colorMap[status] || '#606266';
};

// 物品类型文案
const getItemTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'Lost': '丢失物品',
    'Found': '拾到物品'
  };
  return typeMap[type] || type;
};

// 时间格式化
const formatTime = (timestamp: Date | string) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 图片加载错误处理
const handleImageError = (event: any) => {
  (event.target as any).src = '/static/default-placeholder.png';
};

// 位置格式化
const formatLocation = (location: string) => {
  if (!location) return '未设置位置';
  return location;
};

// 定义操作按钮接口
interface ActionButton {
  type: string;
  text: string;
  action: (item: BaseItem) => void;
}

// 根据状态获取操作按钮
const getActionButtons = (item: BaseItem): ActionButton[] => {
  const actions: ActionButton[] = [];
  
  switch(item.status) {
    case 1: // 未通过
      actions.push({
        type: 'delete',
        text: '删除',
        action: handleDelete
      });
      break;
      
    case 2: // 通过
      actions.push({
        type: 'detail',
        text: '详情',
        action: handleDetail
      });
      actions.push({
        type: 'offline',
        text: '下架',
        action: handleOffline
      });
      actions.push({
        type: 'delete',
        text: '删除',
        action: handleDelete
      });
      break;
      
    case 3: // 完成
      actions.push({
        type: 'delete',
        text: '删除',
        action: handleDelete
      });
      break;
      
    case 4: // 下架
      actions.push({
        type: 'online',
        text: '上架',
        action: handleOnline
      });
      actions.push({
        type: 'delete',
        text: '删除',
        action: handleDelete
      });
      break;
      
    case 5: // 驳回
      actions.push({
        type: 'delete',
        text: '删除',
        action: handleDelete
      });
      break;
  }
  
  return actions;
};

// 处理按钮点击事件
const handleAction = (btn: ActionButton, item: BaseItem) => {
  btn.action(item);
};

// 发布物品
const handlePublish = () => {
  uni.navigateTo({ url: '/components/posts' });
};

// 删除物品
const handleDelete = (item: BaseItem) => {
	uni.showToast({
		title:'删除暂不可用',
		icon:'error'
	})
  /* uni.showModal({
    title: '确认删除',
    content: '确定要删除这条发布吗？此操作不可恢复',
    success: async (res) => {
      if (res.confirm) {
        try {
          isLoading.value = true;
          const res = await uni.request({
            url: `${BASE_URL}/${item.itemType}item/delete/${item.itemId}`,
            method: 'DELETE',
            header: { 'Content-Type': 'application/json' }
          });
          const result = res.data;
          if (result.code === 200) {
            itemList.value = itemList.value.filter(i => i.itemId !== item.itemId);
            uni.showToast({ title: '删除成功', icon: 'success' });
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'fail' });
          }
        } catch (err: any) {
          uni.showToast({ title: err.message || '网络错误，删除失败', icon: 'fail' });
          console.error('删除发布失败', err);
        } finally {
          isLoading.value = false;
        }
      }
    }
  }); */
};

// 查看详情
const handleDetail = (item: BaseItem) => {
	if(item.itemType==='Lost'){
		uni.navigateTo({
			url:`/pages/item-detail/Lostdetail?id=${item.itemId}`
		})
	}else{
		uni.navigateTo({
			url:`/pages/item-detail/Founddetail?id=${item.itemId}`
		})
	}
};

// 下架物品
const handleOffline = (item: BaseItem) => {
  uni.showModal({
    title: '确认下架',
    content: '确定要下架这条发布吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          isLoading.value = true;
          const res = await uni.request({
            url: `${BASE_URL}/${item.itemType}Item/approve/${item.itemId}?status=4`,
            method: 'PUT',
            header: { 'Content-Type': 'application/json' }
          });
          const result = res.data;
          if (result.code === 200) {
            const index = itemList.value.findIndex(i => i.itemId === item.itemId);
            if (index !== -1) {
              itemList.value[index].status = 4;
            }
            uni.showToast({ title: '下架成功', icon: 'success' });
          } else {
            uni.showToast({ title: result.message || '下架失败', icon: 'fail' });
          }
        } catch (err: any) {
          uni.showToast({ title: err.message || '网络错误，下架失败', icon: 'fail' });
          console.error('下架发布失败', err);
        } finally {
          isLoading.value = false;
        }
      }
    }
  });
};

// 上架物品
const handleOnline = (item: BaseItem) => {
  uni.showModal({
    title: '确认上架',
    content: '确定要上架这条发布吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          isLoading.value = true;
          const res = await uni.request({
            url: `${BASE_URL}/${item.itemType}Item/approve/${item.itemId}?status=2`,
            method: 'PUT',
            header: { 'Content-Type': 'application/json' }
          });
          const result = res.data;
          if (result.code === 200) {
            const index = itemList.value.findIndex(i => i.itemId === item.itemId);
            if (index !== -1) {
              itemList.value[index].status = 2;
            }
            uni.showToast({ title: '上架成功', icon: 'success' });
          } else {
            uni.showToast({ title: result.message || '上架失败', icon: 'fail' });
          }
        } catch (err: any) {
          uni.showToast({ title: err.message || '网络错误，上架失败', icon: 'fail' });
          console.error('上架发布失败', err);
        } finally {
          isLoading.value = false;
        }
      }
    }
  });
};

// 鼠标悬停
const handleMouseEnter = (id: number) => {
  hoveredItem.value = id;
};
const handleMouseLeave = () => {
  hoveredItem.value = null;
};

// 页面生命周期
onLoad(() => { loadMyItems(); });
onShow(() => { loadMyItems(); });

// 加载数据
const loadMyItems = async () => {
  isLoading.value = true;
  errorMsg.value = null;
  try {
    const userId = uni.getStorageSync('userId');
    const res = await uni.request({
      url: `${BASE_URL}/baseItem/getAll/${userId}`,
      method: 'GET',
      header: { 'Content-Type': 'application/json' }
    });
    const result = res.data;
    if (result.code === 200) {
      itemList.value = result.data || [];
      console.log('加载我的发布列表成功', itemList.value);
    } else {
      errorMsg.value = result.message || '获取数据失败';
    }
  } catch (err: any) {
    errorMsg.value = err.message || '网络错误，请稍后再试';
    console.error('获取我的发布列表失败', err);
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
page {
  height: 100%;
  background-color: #F8FAFC;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 顶部标题栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  background-color: #4A90E2;
  height: 90rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}
.header-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #FFFFFF;
}
.publish-btn-container {
  display: flex;
  align-items: center;
}
.publish-btn {
  margin: 0;
  color: #FFFFFF;
  border-color: #FFFFFF;
  background-color: transparent;
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
}
.publish-btn-text {
  margin-left: 8rpx;
}

/* 状态提示栏 */
.loading-banner, .error-banner {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  width: 100%;
  box-sizing: border-box;
}
.loading-banner {
  background-color: #EBF5FF;
  border-bottom: 1rpx solid #E8F2FF;
}
.error-banner {
  background-color: #FFF3F3;
  border-bottom: 1rpx solid #FFE0E0;
}
.banner-text, .error-text {
  margin-left: 16rpx;
  font-size: 28rpx;
}
.banner-text { color: #4A90E2; font-weight: 500; }
.error-text { color: #F56C6C; font-weight: 500; }

/* 筛选标签栏 */
.filter-tabs {
  display: flex;
  padding: 20rpx 0;
  background-color: #FFFFFF;
  border-bottom: 1rpx solid #F2F7FF;
  box-shadow: 0 2rpx 10rpx rgba(74, 144, 226, 0.05);
  width: 100%;
  box-sizing: border-box;
  overflow-x: auto;
  white-space: nowrap;
}
.tab-item {
  padding: 16rpx 24rpx;
  font-size: 28rpx;
  color: #667085;
  border-radius: 40rpx;
  transition: all 0.3s ease;
  flex: 0 0 auto;
  text-align: center;
  background-color: #F9FAFB;
  margin: 0 10rpx;
}
.tab-item.active {
  background-color: #4A90E2;
  color: #FFFFFF;
  box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.2);
}

/* 列表容器 */
.list-container {
  flex: 1;
  overflow: auto;
  padding: 20rpx 30rpx;
  width: 100%;
  box-sizing: border-box;
}

/* 空状态 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 160rpx 0;
  width: 100%;
}
.empty-text {
  margin-top: 24rpx;
  font-size: 32rpx;
  color: #4A90E2;
  font-weight: 500;
}
.empty-subtext {
  margin-top: 12rpx;
  font-size: 26rpx;
  color: #9CA3AF;
}

/* 物品卡片 */
.item-card {
  background-color: #FFFFFF;
  border-radius: 20rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.08);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: row;
  padding: 24rpx;
}
.item-card.card-hover {
  transform: translateY(-4rpx);
  box-shadow: 0 12rpx 32rpx rgba(74, 144, 226, 0.12);
}

/* 图片区域 */
.item-image-container {
  width: 200rpx;
  height: 200rpx;
  position: relative;
  margin-right: 24rpx;
  border-radius: 12rpx;
  overflow: hidden;
  flex-shrink: 0;
}
.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.item-type-tag {
  position: absolute;
  bottom: 12rpx;
  left: 12rpx;
  color: #FFFFFF;
  padding: 6rpx 12rpx;
  border-radius: 4rpx;
  font-size: 24rpx;
  font-weight: 500;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

/* 信息区域 */
.item-info-container {
  flex: 1;
  display: flex;
  width: 200rpx;
  flex-direction: column;
  min-height: 200rpx;
}
.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}
.item-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1F2937;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-right: 16rpx;
}
.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  min-width: 80rpx;
  text-align: center;
  flex-shrink: 0;
}
.item-desc {
  font-size: 28rpx;
  color: #4B5563;
  line-height: 1.6;
  /* 调整为显示3行，避免丢失物品描述显示不全 */
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  margin-bottom: 16rpx;
}

/* 位置信息 */
.item-location {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #F3F4F6;
}
.location-text {
  font-size: 28rpx;
  color: #4B5563;
  margin-left: 12rpx;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 底部操作栏 */
.item-footer {
  display: flex;
  flex-direction: column;
  margin-top: auto;
  padding-top: 16rpx;
  border-top: 1rpx solid #F3F4F6;
}
.footer-time {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding-bottom: 8rpx;
}
.item-time {
  font-size: 24rpx;
  color: #9CA3AF;
}
.action-btns-row {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  margin-top: 8rpx;
}
.action-buttons {
  display: flex;
  width: 100%;
  gap: 8rpx;
}

/* 按钮基础样式 */
.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 0;
  font-size: 26rpx;
  border-radius: 12rpx;
  cursor: pointer;
  transition: all 0.3s ease;
  box-sizing: border-box;
  height: 64rpx;
  font-weight: 500;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.action-btn:active {
  transform: scale(0.96);
}
.action-btn-text {
  margin: 0;
}

/* 按钮宽度控制 */
.single-btn {
  width: 100%;
}
.double-btn {
  width: 50%;
}
.triple-btn {
  width: 33.33%;
}

/* 按钮颜色样式 */
.btn-delete {
  background-color: #FFF2F0;
  color: #F5222D;
}
.btn-delete:hover {
  background-color: #FFE5E0;
}
.btn-offline, .btn-online {
  background-color: #FFF7E6;
  color: #FAAD14;
}
.btn-offline:hover, .btn-online:hover {
  background-color: #FFF2CC;
}
.btn-detail {
  background-color: #E8F3FF;
  color: #4A90E2;
}
.btn-detail:hover {
  background-color: #D6E8FF;
}

/* 无操作按钮状态 */
.no-actions {
  font-size: 24rpx;
  color: #9CA3AF;
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  background-color: #F5F7FA;
  width: 100%;
  text-align: center;
}

/* 底部空白区域，防止内容被底部导航栏遮挡 */
.bottom-space {
  height: 100rpx;
}
</style>